#!/bin/bash

# 定义输出HTML文件路径
OUTPUT_FILE="/data/jenkins-slave/workspace/testing/Xm_Auto_Perf/testPage/performance_report.html"


# 创建HTML框架（使用上面的HTML内容）
cat > $OUTPUT_FILE << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>性能压测报告系统</title>
    <style>
        :root {
            --primary-color: #3498db;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --light-bg: #f8f9fa;
            --border-color: #dee2e6;
            --text-color: #333;
            --text-light: #6c757d;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background-color: #f5f7fa;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        header {
            background: linear-gradient(135deg, #1a2a6c, #2a5298);
            color: white;
            padding: 25px 30px;
            position: relative;
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        
        h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .module-selector {
            background: rgba(255, 255, 255, 0.15);
            border-radius: 4px;
            padding: 8px 15px;
            display: inline-flex;
            align-items: center;
        }
        
        .module-selector select {
            background: transparent;
            border: none;
            color: white;
            font-size: 16px;
            padding: 5px;
            outline: none;
            cursor: pointer;
        }
        
        .module-selector select option {
            color: #333;
        }
        
        .report-info {
            display: flex;
            justify-content: space-between;
            background-color: var(--light-bg);
            padding: 15px 30px;
            border-bottom: 1px solid var(--border-color);
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-size: 14px;
            color: var(--text-light);
            margin-bottom: 5px;
        }
        
        .info-value {
            font-size: 16px;
            font-weight: 500;
        }
        
        .filters {
            padding: 20px 30px;
            background: white;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }
        
        .filter-group {
            display: flex;
            align-items: center;
        }
        
        .filter-group label {
            margin-right: 10px;
            font-size: 14px;
            color: var(--text-light);
        }
        
        .filter-group select, .filter-group input {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
        }
        
        .btn {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        
        .btn:hover {
            background-color: #2980b9;
        }
        
        .btn-icon {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            background-color: var(--light-bg);
        }
        
        th {
            padding: 16px 20px;
            text-align: left;
            font-weight: 600;
            color: var(--text-light);
            border-bottom: 2px solid var(--border-color);
        }
        
        td {
            padding: 14px 20px;
            border-bottom: 1px solid var(--border-color);
        }
        
        tbody tr {
            transition: background-color 0.2s;
        }
        
        tbody tr:hover {
            background-color: rgba(52, 152, 219, 0.05);
        }
        
        .status {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 500;
        }
        
        .status-completed {
            background-color: rgba(46, 204, 113, 0.15);
            color: var(--success-color);
        }
        
        .status-generating {
            background-color: rgba(243, 156, 18, 0.15);
            color: var(--warning-color);
        }
        
        .status-failed {
            background-color: rgba(231, 76, 60, 0.15);
            color: var(--danger-color);
        }
        
        .report-link {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .report-link:hover {
            text-decoration: underline;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            padding: 25px;
            border-top: 1px solid var(--border-color);
        }
        
        .page-btn {
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid var(--border-color);
            background: white;
            color: var(--text-color);
            margin: 0 4px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .page-btn:hover, .page-btn.active {
            background-color: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .page-btn.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--text-light);
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 20px;
            color: #bdc3c7;
        }
        
        .empty-state h3 {
            font-size: 20px;
            margin-bottom: 10px;
            color: var(--text-color);
        }
        
        .empty-state p {
            max-width: 500px;
            margin: 0 auto 20px;
        }
        
        footer {
            text-align: center;
            padding: 20px;
            color: var(--text-light);
            font-size: 14px;
            border-top: 1px solid var(--border-color);
        }
        
        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .module-selector {
                margin-top: 15px;
            }
            
            .report-info {
                flex-direction: column;
                gap: 10px;
            }
            
            .filters {
                flex-direction: column;
                align-items: flex-start;
            }
            
            th, td {
                padding: 12px 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="header-content">
                <div>
                    <h1>性能压测报告系统</h1>
                    <p>实时监控与分析API性能指标</p>
                </div>
                <div class="module-selector">
                    <span>当前模块：</span>
                    <select id="module-select">
                        <option value="user">用户服务模块</option>
                        <option value="order">订单处理模块</option>
                        <option value="payment">支付网关模块</option>
                        <option value="inventory">库存管理模块</option>
                    </select>
                </div>
            </div>
        </header>
        
        <div class="report-info">
            <div class="info-item">
                <span class="info-label">最后更新时间</span>
                <span class="info-value" id="last-updated">2025-10-21 09:56:33</span>
            </div>
            <div class="info-item">
                <span class="info-label">总报告数</span>
                <span class="info-value" id="total-reports">0</span>
            </div>
            <div class="info-item">
                <span class="info-label">平均响应时间</span>
                <span class="info-value" id="avg-response">-- ms</span>
            </div>
        </div>
        
        <div class="filters">
            <div class="filter-group">
                <label for="date-filter">日期范围：</label>
                <input type="date" id="start-date">
                <span style="margin: 0 10px;">至</span>
                <input type="date" id="end-date">
            </div>
            
            <div class="filter-group">
                <label for="status-filter">状态：</label>
                <select id="status-filter">
                    <option value="all">全部状态</option>
                    <option value="completed">已完成</option>
                    <option value="generating">生成中</option>
                    <option value="failed">失败</option>
                </select>
            </div>
            
            <div class="filter-group">
                <label for="api-filter">API筛选：</label>
                <select id="api-filter">
                    <option value="all">全部API</option>
                    <option value="login">用户登录</option>
                    <option value="profile">用户资料</option>
                    <option value="order">创建订单</option>
                </select>
            </div>
            
            <button class="btn btn-icon">
                <i>🔍</i> 筛选
            </button>
            
            <button class="btn btn-icon" style="margin-left: auto; background-color: var(--success-color);">
                <i>📊</i> 生成新报告
            </button>
        </div>
        
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>API</th>
                        <th>压测报告地址</th>
                        <th>报告生成状态</th>
                    </tr>
                </thead>
                <tbody id="report-data">
                    <!-- 数据将通过JavaScript动态填充 -->
                    <tr class="empty-row">
                        <td colspan="4">
                            <div class="empty-state">
                                <div>📊</div>
                                <h3>暂无压测报告数据</h3>
                                <p>当前没有可显示的压测报告，请尝试选择其他模块或生成新的压测报告。</p>
                                <button class="btn" style="background-color: var(--success-color);">
                                    开始新的压测
                                </button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <div class="pagination">
            <button class="page-btn disabled">«</button>
            <button class="page-btn active">1</button>
            <button class="page-btn">2</button>
            <button class="page-btn">3</button>
            <button class="page-btn">»</button>
        </div>
        
        <footer>
            <p>性能压测报告系统 &copy; 2025 | 数据每5分钟自动更新 | 技术支持: tech@example.com</p>
        </footer>
    </div>

    <script>
        // 更新当前时间
        function updateDateTime() {
            const now = new Date();
            const formattedDate = now.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-');
            
            document.getElementById('last-updated').textContent = formattedDate;
        }
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            updateDateTime();
            
            // 设置默认日期为今天
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('start-date').value = today;
            document.getElementById('end-date').value = today;
            
            // 模块选择事件
            document.getElementById('module-select').addEventListener('change', function() {
                // 在实际应用中，这里会加载新模块的数据
                document.querySelector('h1').innerHTML = `${this.options[this.selectedIndex].text} 性能压测报告`;
            });
        });
    </script>
</body>
</html>
EOF

# 准备性能压测数据
LAST_UPDATED=$(date "+%Y-%m-%d %H:%M:%S")
TOTAL_REPORTS=42
AVG_RESPONSE="128ms"

# 替换报告信息
sed -i "s/id=\"last-updated\">.*</id=\"last-updated\">$LAST_UPDATED</" $OUTPUT_FILE
sed -i "s/id=\"total-reports\">.*</id=\"total-reports\">$TOTAL_REPORTS</" $OUTPUT_FILE
sed -i "s/id=\"avg-response\">.*</id=\"avg-response\">$AVG_RESPONSE</" $OUTPUT_FILE

# 准备表格数据（从CSV文件读取）
DATA_FILE="/data/jenkins-slave/workspace/testing/Xm_Auto_Perf/testPage/pageperformance_data.csv"
TABLE_ROWS=""

# 调试信息
echo "检查数据文件: $DATA_FILE"
if [ -f "$DATA_FILE" ]; then
    echo "文件存在性: 文件存在"
    echo "文件内容:"
    cat "$DATA_FILE"
else
    echo "文件存在性: 文件不存在"
fi

# 如果数据文件存在，生成表格行
if [ -f "$DATA_FILE" ]; then
    echo "找到数据文件，开始处理..."
    
    # 创建临时文件处理跳过标题行
    TEMP_FILE=$(mktemp)
    tail -n +2 "$DATA_FILE" > "$TEMP_FILE"
    
    # 调试：显示临时文件内容
    echo "临时文件内容:"
    cat "$TEMP_FILE"
    
    # 使用进程替换避免子shell问题
    while IFS= read -r line; do
        # 使用逗号分隔字段
        timestamp=$(echo "$line" | cut -d',' -f1 | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        api=$(echo "$line" | cut -d',' -f2 | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        report_url=$(echo "$line" | cut -d',' -f3 | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        status=$(echo "$line" | cut -d',' -f4 | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        
        echo "处理行: timestamp='$timestamp', api='$api', report_url='$report_url', status='$status'"
        
        # 根据状态设置CSS类
        case $status in
            completed) status_class="status-completed" ;;
            generating) status_class="status-generating" ;;
            failed) status_class="status-failed" ;;
            *) status_class="status-generating" ;;
        esac
        
        TABLE_ROWS+="<tr>
            <td>$timestamp</td>
            <td>$api</td>
            <td><a href=\"$report_url\" class=\"report-link\" target=\"_blank\">📊 查看报告</a></td>
            <td><span class=\"status $status_class\">$status</span></td>
        </tr>"
    done < "$TEMP_FILE"  # 使用文件重定向而不是管道
    
    # 清理临时文件
    rm "$TEMP_FILE"
    
    echo "生成的表格行:"
    echo "$TABLE_ROWS"
    echo "表格行长度: ${#TABLE_ROWS}"
else
    echo "警告: 数据文件不存在: $DATA_FILE"
fi

# 替换表格内容
if [ -n "$TABLE_ROWS" ]; then
    echo "开始替换表格内容..."
    
    # 创建临时文件来存储新的表格内容
    TEMP_HTML=$(mktemp)
    
    # 使用awk来替换表格内容
    awk -v new_rows="$TABLE_ROWS" '
    /<tbody id="report-data">/ {
        print
        print new_rows
        # 跳过空行
        while (getline > 0) {
            if (/<\/tbody>/) {
                print
                break
            }
        }
        next
    }
    /<tr class="empty-row">/ {
        # 跳过空行
        while (getline > 0) {
            if (/<\/tr>/) break
        }
        next
    }
    { print }
    ' "$OUTPUT_FILE" > "$TEMP_HTML"
    
    # 用临时文件替换原文件
    mv "$TEMP_HTML" "$OUTPUT_FILE"
    
    echo "表格内容替换完成"
else
    echo "警告: 没有找到数据或数据文件为空"
    echo "TABLE_ROWS 值为: $TABLE_ROWS"
    echo "TABLE_ROWS 长度: ${#TABLE_ROWS}"
fi

echo "性能报告已生成: $OUTPUT_FILE"